package com.karry.yl.service.filing.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.karry.commons.base.impl.SuperServiceImpl;
import com.karry.yl.dao.baseinfo.OrganizationMapper;
import com.karry.yl.dao.filing.FilingMapper;
import com.karry.yl.domain.baseinfo.Employee;
import com.karry.yl.domain.baseinfo.Organization;
import com.karry.yl.domain.elder.Elderly;
import com.karry.yl.domain.filing.Filing;
import com.karry.yl.domain.mz.MzDepartment;
import com.karry.yl.service.baseinfo.EmployeeService;
import com.karry.yl.service.elder.ElderlyService;
import com.karry.yl.service.filing.FilingService;
import com.karry.yl.service.mz.MzDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 备案记录业务层
 *
 * @author Administrator
 */
@Service
public class FilingServiceImpl extends SuperServiceImpl<FilingMapper, Filing> implements FilingService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private FilingMapper filingMapper;

    @Autowired
    private MzDepartmentService mzDepartmentService;

    @Autowired
    private ElderlyService elderlyService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void filingSubmitted(Filing filing, Long orgId) {
        //根据民政局id查詢民政部
        String code = filing.getMzCode();
        MzDepartment mzDepartment = mzDepartmentService.selectByCode(code);
        String departmentName = mzDepartment.getDepartmentName();
        filing.setMzName(departmentName);
        filing.setMzCode(code);
        //跟新机构表的备案状态
        Organization organization = organizationMapper.selectById(orgId);
        organization.setMzCode(code);
        organization.setMzName(departmentName);
        organization.setFilingStart(1);//1表示待审核
        organization.setShangBaoDate(new Date());
        organizationMapper.update(organization, new EntityWrapper<Organization>().eq("id", orgId));
        //添加备案记录数据
        filingMapper.insert(filing);
        //当民证部门备案成功时，同步老人的信息
        //查询该机构下的所有老人
        List<Elderly> elderlies = elderlyService.selectList(new EntityWrapper<Elderly>().eq("orgId", orgId).eq("deleted", false));
        if(elderlies.size()>0&&elderlies!=null){
            for (Elderly elderly : elderlies) {
                elderly.setMzCode(code);
                elderly.setMzName(departmentName);
                elderlyService.updateById(elderly);
            }
        }

    }
}
